package info.niwota.webshot;

import info.niwota.webshot.KeyTracker.Stage;
import info.niwota.webshot.KeyTracker.State;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebBackForwardList;

/**
 * @author qiangli
 * 
 */
public class WebSnapshotActivity extends WebBaseActivity implements
		KeyTracker.OnKeyTracker {
	private static final String TAG = "WebSnapshotActivity";
	
//	private final SensorAdapter sensorAdapter = new SensorAdapter() {
//
//		@Override
//		public boolean onTilt(SensorEvent event, int direction) {
//			if (Debug.DEBUG) {
//				Log.d(TAG, "onTilt event: " + event + " dir: " + direction);
//			}
//			return false;
//		}
//
//		@Override
//		public boolean onFlip(SensorEvent event) {
//			if (Debug.DEBUG) {
//				Log.d(TAG, "onFlip event: " + event );
//			}
//			return false;
//		}
//
//		@Override
//		public boolean onLongFlip(SensorEvent event) {
//			if (Debug.DEBUG) {
//				Log.d(TAG, "onLongFlip event: " + event );
//			}
//			return false;
//		}
//
//		@Override
//		public boolean onShake(SensorEvent event, float speed) {
//			if (Debug.DEBUG) {
//				Log.d(TAG, "onShake event: " + event );
//			}
//			return false;
//		}
//
//		@Override
//		public boolean onFaceUp(SensorEvent event) {
//			return false;
//		}
//
//		@Override
//		public boolean onFaceDown(SensorEvent event) {
//			return false;
//		}
//		
//	};

	private boolean ezBoardingAvailable;

	private final KeyTracker mKeyTracker = new KeyTracker(this);

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//
		requestWindowFeature(Window.FEATURE_PROGRESS);
		requestWindowFeature(Window.FEATURE_LEFT_ICON);

		setContentView(R.layout.browser);

		getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
				R.drawable.browser);
		//
		initRes(savedInstanceState);
		initWebview(savedInstanceState);
		init(savedInstanceState);
		
		//SensorUtil.initSensor(this, sensorAdapter);
	}

	@Override
	protected void onPause() {
		super.onPause();
		
		//SensorUtil.stopSensor();
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		//SensorUtil.startSensor();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean handled = mKeyTracker.doKeyDown(keyCode, event);
		return (handled || super.onKeyDown(keyCode, event));
		//
		// if (keyCode == KeyEvent.KEYCODE_BACK) {
		// doBack();
		// return true;
		// }
		// return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void doBack() {
		if (Debug.DEBUG) {
			Log.d(TAG, "doBack");
		}
		try {
			if (frameSnapshot.getVisibility() == View.VISIBLE) {
				showWeb();
			} else {
				// frameWeb visible
				webview.stopLoading();
				//
				WebBackForwardList l = webview.copyBackForwardList();
				int idx = (l == null ? -1 : l.getCurrentIndex());
				boolean b = (webview.canGoBack() && idx > 0);
				if (b) {
					History.showHistoryBackDialog(this, webview, l);
				} else {
					if (backQuit) {
						doQuit();
					} else {
						goHome();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		return mKeyTracker.doKeyUp(keyCode, event)
				|| super.onKeyUp(keyCode, event);
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	protected void initRes(Bundle savedInstanceState) {
		super.initRes(savedInstanceState);
		//
		ezBoardingAvailable = (Utils.isEZBoardingAvailable(this));
		btnAccept.setVisibility(ezBoardingAvailable ? View.VISIBLE : View.GONE);
	}

	@Override
	protected void doAccept() {
		try {
			// add to EZ Boarding
			Uri uri = (imagefile == null ? null : Uri.parse("file://"
					+ imagefile.getPath()));
			Intent i = Utils.createEZBoardingIntent();
			i.setData(uri);
			i.putExtra("url", webview.getUrl());
			i.putExtra("title", webview.getTitle());
			startActivity(i);
			//
			addImage();
		} catch (Exception e) {
			e.printStackTrace();
		}
		showWeb();
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		int action = event.getAction();
		int keyCode = event.getKeyCode();
		switch (keyCode) {
		case KeyEvent.KEYCODE_SEARCH:
			doSearch();
			return true;
		case KeyEvent.KEYCODE_VOLUME_UP:
			if (action == KeyEvent.ACTION_DOWN) {
				if (enableZoomVol) {
					webview.zoomIn();
				}
			}
			return true;
		case KeyEvent.KEYCODE_VOLUME_DOWN:
			if (action == KeyEvent.ACTION_DOWN) {
				if (enableZoomVol) {
					webview.zoomOut();
				}
			}
			return true;
		default:
			return super.dispatchKeyEvent(event);
		}
	}

	private void doSearch() {
		try {
			webview.emulateShiftHeld();
			
			//Method m = WebView.class.getMethod("emulateShiftHeld", null);
			//m.invoke(webview, null);
			
		} catch (Exception e) {
			e.printStackTrace();
			
			KeyEvent ke = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
					KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
			ke.dispatch(webview);
		}
	}

	public State onKeyTracker(int keyCode, KeyEvent event, Stage stage,
			int duration) {
		if (Debug.DEBUG) {
			Log.d(TAG, "onKeyTracker keyCode: " + keyCode + " event: " + event + " stage: " + stage);
		}
		
		if (stage == KeyTracker.Stage.UP) {
			ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			CharSequence str = cm.getText();
			Log.d(TAG, "onKeyTracker: " + str);
		}
		//
//		if (enableZoomVol && ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)
//				|| (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN))) {
//			if (stage == KeyTracker.Stage.UP || stage == KeyTracker.Stage.LONG_REPEAT) {
//				if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
//					webview.zoomIn();
//				} else {
//					webview.zoomOut();
//				}
//				return KeyTracker.State.DONE_TRACKING;
//			}
//			return KeyTracker.State.KEEP_TRACKING;
//		}
		//
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (stage == KeyTracker.Stage.LONG_REPEAT) {
				doQuit();
				return KeyTracker.State.DONE_TRACKING;
			} else if (stage == KeyTracker.Stage.UP) {
				doBack();
				return KeyTracker.State.DONE_TRACKING;
			}
			return KeyTracker.State.KEEP_TRACKING;
		}
		return KeyTracker.State.NOT_TRACKING;
	}
}
